<?php

declare(strict_types=1);

namespace App\Controller\Kpi;

use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Annotation\Scene;

use Qbhy\HyperfAuth\AuthManager;
use Hyperf\Redis\Redis;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use App\Request\PassportRequest;

use App\Service\SysUser as SysUserService;

#[AutoController]
class PassportController extends AbstractController
{
    #[Inject]
    protected AuthManager $auth;

    #[Inject]
    private Redis $redis;
    
    /**
     * 登录
     */
    #[Scene(scene: 'login', argument: 'request')]
    public function login(PassportRequest $request)
    {
        // 获取通过验证的表单数据
        $params = $request->validated();
        $phrase = $this->redis->get('phrase_'.$params['key']);
        
        if(!$phrase || $phrase != trim($params['code'])){
            return $this->returnError('验证码错误');
        }

        $user_service = new SysUserService();
        $sysuser = $user_service->login($params);
        $token = $this->auth->guard('jwt')->login($sysuser);
        $info = $user_service->getInfo($this->auth->guard('jwt')->id($token));
        if($info){
            return $this->returnSuccess(['token' => $token,'user'=>$info, 'date' => date('Y-m-d H:i:s')], '登录成功');
        }else{
            return $this->returnError('登录出错啦，请联系管理员');
        }
    }

    public function captcha()
    {
        $phraseBuilder = new PhraseBuilder(4, '0123456789');
        $builder = new CaptchaBuilder(null, $phraseBuilder);
        $builder->build();
        $builder->setBackgroundColor(220, 210, 230);
        $captcha = $builder->inline();  //输出base64格式图片
        $code = $builder->getPhrase();  //验证码

        // 生成唯一的key标识符
        $key = uniqid('captcha');
        $this->redis->set('phrase_' . $key, $code, 120);

        return $this->returnSuccess(compact('captcha', 'code', 'key'), '成功');
    }

    // 退出登录
    public function logout()
    {
        $this->auth->guard('jwt')->logout();
        return $this->returnSuccess([], '退出登录');
    }
}
